#!/usr/bin/env python
# coding: utf-8

import pandas as pd
import os
import numpy as np
import math
from sklearn.linear_model import LogisticRegression

def get_woe_data(df,cut):
    rate=float(df['target'].sum())/float((df['target'].count()-df['target'].sum()))
    grouped=df['target'].groupby(cut,as_index = True).value_counts()
    woe=np.log(grouped.unstack().iloc[:,1]/grouped.unstack().iloc[:,0]/rate)
    return woe

def replace_data(cut,cut_woe):
    a=[]
    for i in cut.unique():
        a.append(i)
        a.sort()
    for m in range(len(a)-1):
        cut.replace(a[m],cut_woe.values[m],inplace=True)
    return cut



if __name__ == '__main__':
    print '---------getting started----------------'
    train_file=pd.read_csv("training_data.csv")
    print '---------training file loaded successfully----------------'
    test_file=pd.read_csv("testing_data.csv")
    print '---------testing file loaded successfully----------------'
    out_path=os.getcwd()+'\\pd and score.csv'
    
    train_df=train_file[['target','loan_1y','balance/credit','delay_5y','amount']]
    test_df=test_file[['target','loan_1y','balance/credit','delay_5y','amount']]
    
    bins1=[float('-inf'),2,4,6,8,10,12,14,16,18,float('inf')]
    bins2=[float('-inf'),0.65,0.70,0.75,0.85,0.90,float('inf')]
    bins3=[float('-inf'),2,4,6,float('inf')]
    bins4=[float('-inf'),35000,40000,50000,60000,float('inf')]
    
    cut1=pd.cut(train_df['loan_1y'],bins1,labels=False)
    cut2=pd.cut(train_df['balance/credit'],bins2,labels=False)
    cut3=pd.cut(train_df['delay_5y'],bins3,labels=False)
    cut4=pd.cut(train_df['amount'],bins4,labels=False)
    
    cut1_woe=get_woe_data(train_df,cut1)
    cut2_woe=get_woe_data(train_df,cut2)
    cut3_woe=get_woe_data(train_df,cut3)
    cut4_woe=get_woe_data(train_df,cut4)
    
    df_train_woe=pd.DataFrame()
    df_train_woe['target']=train_df['target']
    df_train_woe['loan_1y']=replace_data(cut1,cut1_woe)
    df_train_woe['balance/credit'] = replace_data(cut2,cut2_woe)
    df_train_woe['delay_5y'] = replace_data(cut3,cut3_woe)
    df_train_woe['amount'] = replace_data(cut4,cut4_woe)
    df_train_woe.dropna(axis=0,inplace=True)
    print '----------training data WOE successfully transformed-------------'
    
    tcut1=pd.cut(test_df['loan_1y'],bins1,labels=False)
    tcut2=pd.cut(test_df['balance/credit'],bins2,labels=False)
    tcut3=pd.cut(test_df['delay_5y'],bins3,labels=False)
    tcut4=pd.cut(test_df['amount'],bins4,labels=False)
    
    tcut1_woe=get_woe_data(train_df,tcut1)
    tcut2_woe=get_woe_data(train_df,tcut2)
    tcut3_woe=get_woe_data(train_df,tcut3)
    tcut4_woe=get_woe_data(train_df,tcut4)
    
    df_test_woe=pd.DataFrame()
    df_test_woe['loan_1y']=replace_data(tcut1,tcut1_woe)
    df_test_woe['balance/credit'] = replace_data(tcut2,tcut2_woe)
    df_test_woe['delay_5y'] = replace_data(tcut3,tcut3_woe)
    df_test_woe['amount'] = replace_data(tcut4,tcut4_woe)
    print '----------testing data WOE successfully transformed-------------'
    
    print '----------LR training...-------------'   
    x_train=df_train_woe.iloc[:,1:]
    y_train=df_train_woe['target']
    x_test=df_test_woe
    model=LogisticRegression()
    clf=model.fit(x_train,y_train)
    coe=clf.coef_
    df_test_woe['linear_y']=-np.dot(x_test,np.transpose(coe[0]))
    
    print '----------computing probability of default...-------------' 
    df_test_woe['pd']=prob=df_test_woe.linear_y.apply(lambda x: 1/(1+math.exp(x)))
    
    print '----------computing credit scores...-------------' 
    factor = 50 / np.log(2)   #factor即为B pd=2/3为临界点时odds=2
    offset = 600 - 50 * np.log(1) / np.log(2)  #offset即为A，基准分值为600，odds翻倍分数增加20
    df_test_woe['score']=offset-factor*np.log(df_test_woe['pd']/(1-df_test_woe['pd']))
    
    print '----------writing PD and Credtit Scores to csv...-------------' 
    out_df = pd.DataFrame()
    out_df['pd']=df_test_woe['pd']
    out_df['score'] = df_test_woe['score']
    out_df.to_csv(out_path)
    print '----------csv file saved.-------------' 
    

